﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UCL;
using UCL.Data;
using UCL.Forms;

namespace DBKit5.UControls
{
    /// <summary>
    /// 2013-6-7 by sutroon
    /// </summary>
    public partial class frmConnectionEdit : Form
    {
        public int RecordID { get; set; }
        public bool ReadOnly { get; set; }
        public Action RefreshHandler { get; set; }

        AppDataHelper adh;
        public frmConnectionEdit()
        {
            InitializeComponent();
            adh = new AppDataHelper();
        }

        private void frmConnectionEdit_Load(object sender, EventArgs e)
        {
            cbProductName.DataSource = new GeneralDataTypeHelper().GetDataBaseNames();
            cbbGroup.SetDataSource(adh.ExecuteTreeTable("select ID, Name,ParentID from tgeneralcatalog where ParentID={0} and ExTags='CONNECTION_GROUP' order by Ordinal", "0"));
            if (RecordID > 0)
            {
                DataTable dt = adh.ExecuteDataTable("select * from tconnections where ID=" + RecordID);
                tbName.Text = dt.GetValue<string>(r => { return r["Name"];});
                tbHostName.Text = dt.GetValue<string>(r => { return r["HostName"];});
                tbLoginID.Text = dt.GetValue<string>(r => { return r["LoginID"];});
                tbPassword.Text = dt.GetValue<string>(r => { return r["Password"];});
                cbProductName.SelectedItem = dt.GetValue<string>(r => { return r["ProductName"];});
                chkIsDefault.Checked = dt.GetValue<string>(r => { return r["IsDefault"];}).ToBoolean();
                tbDatabase.Text = dt.GetValue<string>(r => { return r["Database"];});
                cbbGroup.SelectedValue = dt.GetValue<string>(r => { return r["GroupID"]; });
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            string msg, connstr;
            if (!TestConnection(out msg, out connstr))
            {
                MessageBox.Show(msg);
                return;
            }
            IDatabaseHelper idh = adh.GetDatabaseHelper(cbProductName.SelectedItem.ToString(), tbHostName.Text, tbLoginID.Text, tbPassword.Text, tbDatabase.Text);
            cbDatabase.DataSource = idh.SO_GetDatabases();
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            string msg, connstr;
            MessageBox.Show(TestConnection(out msg, out connstr) ? "连接成功" : msg);
        }
        /// <summary>
        /// 检测数据库连接
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="connstr"></param>
        /// <returns></returns>
        private bool TestConnection(out string msg, out string connstr)
        {
            msg = string.Empty; connstr = string.Empty;
            DataModule dm;
            if (!this.CheckForm(out dm)) return false;
            IDatabaseHelper idh = adh.GetDatabaseHelper(cbProductName.SelectedItem.ToString(), tbHostName.Text, tbLoginID.Text, tbPassword.Text, tbDatabase.Text);
            if (idh == null) return false;
            return idh.TestConnection(out msg);
        }

        /// <summary>
        /// 检测表单数据并返回数据模型实例
        /// </summary>
        /// <param name="dm"></param>
        /// <returns></returns>
        private bool CheckForm(out DataModule dm)
        {
            dm = new DataModule("tconnections", adh);
            dm.AddParam("Name", tbName.Text, "名称未填写");
            dm.AddParam("HostName", tbHostName.Text, "服务器名称未填写");
            dm.AddParam("ProductName", cbProductName.SelectedItem, "数据库类型未选择");
            dm.AddParam("IsDefault", chkIsDefault.Checked);
            dm.AddParam("GroupID", cbbGroup.GetSelectedValue());
            if (cbProductName.SelectedItem.ToString() != "SQLite")
            {
                dm.AddParam("LoginID", tbLoginID.Text, "登录名未填写");
                dm.AddParam("Password", tbPassword.Text, "密码未填写");
                dm.AddParam("Port", tbPort.Text, "服务器端口未填写", "int");
                dm.AddParam("Database", tbDatabase.Text);
            }
            if (dm.MessageSet.Count > 0)
            {
                MessageBox.Show(dm.GetError());
                return false;
            }
            return true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (cbProductName.SelectedItem == null)
            {
                MessageBox.Show("数据库类型未选择");
                return;
            }
            DataModule dm;
            if (!this.CheckForm(out dm)) return;
            bool result = RecordID > 0 ? dm.Update("ID=" + RecordID) : dm.Insert();
            MessageBox.Show(result ? "保存成功" : dm.GetError());
            if (result)
            {
                if (RefreshHandler != null) RefreshHandler();
                this.Close();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cbProductName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbProductName.SelectedIndex == -1) return;
            string pdtname = cbProductName.SelectedItem.ToString();
            if (pdtname.IsIn("SQLite", "Access"))
            {
                tbLoginID.Enabled = false;
                tbPassword.Enabled = false;
                tbDatabase.Enabled = false;
                cbDatabase.Enabled = false;
                btnRefresh.Enabled = false;
                tbPort.Clear();
                tbPort.Enabled = false;
                btnPickFile.Visible = true;
            }
            else
            {
                tbLoginID.Enabled = true;
                tbPassword.Enabled = true;
                tbDatabase.Enabled = true;
                cbDatabase.Enabled = true;
                btnRefresh.Enabled = true;
                tbPort.Enabled = true;
                switch (pdtname)
                {
                    case "MySQL":
                        tbPort.Text = "3306";
                        break;
                    case "SQLServer":
                        tbPort.Text = "1433";
                        break;
                }
                btnPickFile.Visible = false;
            }
        }

        private void btnPickFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog() { FileName = tbHostName.TextLength > 0 ? tbHostName.Text : Application.StartupPath };
            if (DialogResult.OK != ofd.ShowDialog()) return;
            tbHostName.Text = ofd.FileName;
            tbName.Text = System.IO.Path.GetFileName(ofd.FileName);
        }

        private void cbDatabase_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbDatabase.SelectedIndex == -1) return;
            tbDatabase.Text = cbDatabase.SelectedItem.ToString();
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            string pdtname = cbProductName.SelectedItem.ToString();
            if (pdtname.IsIn("SQLite", "Access"))
            {
                tbName.Text = System.IO.Path.GetFileName(tbHostName.Text);
            }
            else
            {
                tbName.Text = tbHostName.Text + ":" + tbDatabase.Text;
            }
        }
    }
}
